package com.example.hshiran;


import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class registerActivity<handler> extends AppCompatActivity {
    private Button button;
    private String path = "https://www.wanandroid.com/user/register";
    private EditText editText1;
    private EditText editText2;
    private EditText editText3;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if(msg.what == 1){
                Toast.makeText(registerActivity.this,"注册成功",Toast.LENGTH_LONG).show();
                AlertDialog alertDialog = new AlertDialog.Builder(registerActivity.this).setTitle("wanandroid")
                        .setTitle("wandroid")
                        .setMessage("是否自动登录？")
                        .setIcon(R.mipmap.bp)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri uri = Uri.parse("https://wanandroid.com");
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                startActivity(intent);
                                removeActivity(registerActivity.this);
                            }
                        })
                        .setNegativeButton("取消",null)
                        .create();
                alertDialog.show();
            }
            else{
                Toast.makeText(registerActivity.this,msg.obj.toString(),Toast.LENGTH_LONG).show();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        editText1 = (EditText) findViewById(R.id.id);
        editText2 = (EditText) findViewById(R.id.pwd);
        editText3 = (EditText) findViewById(R.id.pwd2);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText1.getText().toString();
                String pwd = editText2.getText().toString();
                String pwd2 = editText3.getText().toString();
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            String s = register(name,pwd,pwd2);
                            JSONObject object = new JSONObject(s);
                            int errorCode = object.optInt("errorCode");
                            String errorMsg = object.optString("errorMsg");
                            Intent intent;
                            Message msg = new Message();
                            msg.obj = errorMsg;
                            if (errorCode == 0) {
                                msg.what = 1;
                            } else {
                                msg.what = 0;
                            }
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }

    private String register(String name, String pwd, String pwd2) {
        try {
            URL url = new URL(path);
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            cn.setRequestMethod("POST");
            cn.setDoOutput(true);
            cn.setUseCaches(false);
            String str = "username=" + URLEncoder.encode(name, "utf-8") + "&password=" + URLEncoder.encode(pwd, "utf-8") + "&repassword=" + URLEncoder.encode(pwd2,"utf-8");
            OutputStream outputStream = cn.getOutputStream();
            outputStream.write(str.getBytes());
            outputStream.flush();
            if (cn.getResponseCode() == 200) {
                InputStream inputStream = cn.getInputStream();
                String s = stream2String(inputStream);
                return s;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return null;
    }

    private String stream2String(InputStream inputStream) {
        BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        try {
            while ((line = bf.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }
    public void removeActivity(Activity activity){
        activity.finish();
    }
}